package net.donotes.bot;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class DoNotesBotServlet extends HttpServlet {
	public static final Logger log = Logger.getLogger(DoNotesBotServlet.class
			.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp) {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		Message msg = null;
		JID fromJid = null;

		try {
			msg = xmpp.parseMessage(req);
			fromJid = msg.getFromJid();

			String body = msg.getBody();
			log.info("Received a message from " + fromJid + " and body = " + body);

			IngBot bot = new IngBot();
			bot.add(body);
		} catch (Exception e) {
			String strStatus = "";

			Message replyMessage = new MessageBuilder().withRecipientJids(
					fromJid).withBody(e.getMessage()).build();

			boolean messageSent = false;
			if (xmpp.getPresence(fromJid).isAvailable()) {
				SendResponse status = xmpp.sendMessage(replyMessage);
				messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
			}

			if (messageSent) {
				strStatus = "Error Message has been sent successfully";
			} else {
				strStatus = "Error Message could not be sent";
			}

			log.info(strStatus);			
			log.log(Level.SEVERE, e.getMessage());
		}
	}
}